'use strict';
const fs = require('fs'); 

const wxFileSrc = require('../config/defaultWxFileSrc').wxFileSrc; 
const _fileSystem = require('../common/fileSystem');
const FILE_TYPE = 'json';

class BuildWxApp {
         constructor (fileName){

                  this.file =  {
                          path : fileName,
                          type : fileName.split(".").reverse()[0],
                          name : fileName.split("/").reverse()[0].split('.')[0] ,
                          root : fileName.replace(fileName.split("/").reverse()[0], "")
                  };
                  if ( this.file.type !== FILE_TYPE ) throw(ERROR[0]);
                  this.appConfig = JSON.parse(fs.readFileSync(this.file.path, "utf-8"));
                  if ( !this.appConfig.pages ) throw(error[1]); 

                  void(this._bulidAppMain());
                  void(this._bulidAppPages());
         }

          _bulidAppMain () {
                  for (let key in wxFileSrc.wxAppContent) {
                          let fileName = this.file.root + this.file.name + key;
                          void(fs.writeFileSync(fileName, wxFileSrc.wxAppContent[key]));
                          if (fs.statSync(fileName)) {
                                  console.log(`INFO: mkfile '${fileName}'success`);
                          } else {
                                  console.log(`INFO: mkfile '${fileName}'error`);
                          }
                  }
          }

          _bulidAppPages () {
                  this.appConfig.pages.forEach((dirName) => {
                          let newDirName = dirName.split("/");
                          void(newDirName.pop());
                          newDirName = this.file.root + newDirName.join("/");
                          console.log(newDirName);
                          console.log(`info: mkdir '${newDirName}'is` + _fileSystem.mkdirsSync(newDirName));
                          for (let key in wxFileSrc.wxPageContent) {
                                  let fileName = this.file.root + dirName + key;
                                  void(fs.writeFileSync(fileName, wxFileSrc.wxPageContent[key]));
                                  if (fs.statSync(fileName)) {
                                          console.log(`INFO: mkfile '${fileName}'success`);
                                  } else {
                                          console.log(`INFO: mkfile '${fileName}'error`);
                                  }
                          }
                  });
          }

}

module.exports = { 
        BuildWxApp 
};